package com.netposa.datawarehouse.aggregator.thirdService;

import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Enumeration;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Configuration
public class NoAuthFeignConfiguration {
   private static final Logger log = LoggerFactory.getLogger(NoAuthFeignConfiguration.class);

   @Bean
   public Feign.Builder feignBuilder() {
      return Feign.builder().requestInterceptor(new RequestInterceptor() {
         public void apply(RequestTemplate requestTemplate) {
            requestTemplate.header("auth", new String[]{"false"});
            requestTemplate.header("tokenId", new String[]{NoAuthFeignConfiguration.this.getServletRequest().getHeader("tokenId")});
            String uuid = String.valueOf(UUID.randomUUID());
            NoAuthFeignConfiguration.log.info("requestId:{}", uuid);
            requestTemplate.header("requestId", new String[]{String.valueOf(UUID.randomUUID())});
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            if (null != attributes && null != attributes.getRequest()) {
               HttpServletRequest request = attributes.getRequest();
               Enumeration headerNames = request.getHeaderNames();
               if (headerNames != null) {
                  while(headerNames.hasMoreElements()) {
                     String name = (String)headerNames.nextElement();
                     String values = request.getHeader(name);
                     requestTemplate.header(name, new String[]{values});
                  }
               }

            }
         }
      });
   }

   private HttpServletRequest getServletRequest() {
      HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
      return request;
   }
}
